/**
 * 
 */
package com.zte.claa.inficombo.csa.app.comm.csif.mina;

import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.apache.mina.filter.codec.demux.MessageEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zte.claa.inficombo.csa.app.comm.csif.mina.msg.CSIFMessage;
import com.zte.claa.inficombo.csa.app.comm.csif.mina.msg.CSIFMsgBody;
import com.zte.claa.inficombo.csa.app.comm.csif.mina.msg.CSIFMsgHead;

/**
 * @author 0283000115
 *
 */
public class CSIFMsgEncoder implements MessageEncoder<CSIFMessage> {
	private Logger LOG = LoggerFactory.getLogger(CSIFMsgEncoder.class);
	// 字符集
	private Charset charset = null;
	private CharsetEncoder charsetEncoder = null;

	public CSIFMsgEncoder(Charset charset) {
		this.charset = charset;
		if (this.charset == null) {
			this.charset = Charset.forName("UTF-8");
		}
		this.charsetEncoder = this.charset.newEncoder();
	}

	/**
	 * 编码方法.
	 */
	public void encode(IoSession session, CSIFMessage message, ProtocolEncoderOutput out) throws Exception {
		LOG.info("Begin encode message for session: " + session.getId()+", msg: "+message);
		IoBuffer buf = IoBuffer.allocate(CSIFMsgHead.getHeadSize()+1, false).setAutoExpand(true);
		// 编码头部.
		CSIFMsgHead head = message.getHead();
		buf.put((byte)head.getBegin());
		buf.put((byte)head.getMainVer());
		buf.put((byte)head.getSubVer());
		buf.putShort((short)head.getMsgLen());
		// 编码body
		CSIFMsgBody body = message.getBody();
		buf.putString(body.getData(), this.charsetEncoder);
		buf.put(body.getEnd());
		// 整理buf，准备输出数据
		buf.flip();
		LOG.info("Finish encoding for session: " + session.getId());
		out.write(buf);
		LOG.info("[send data]="+buf.getHexDump());
		buf.free();
		buf = null;
	}

}
